package com.mis.clothespos.controller;


import com.mis.clothespos.common.AjaxResult;
import com.mis.clothespos.common.BaseController;
import com.mis.clothespos.shiro.common.ShiroUtils;
import com.mis.clothespos.shiro.user.domain.User;
import com.mis.clothespos.shiro.user.service.loginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@Controller
public class LoginController extends BaseController{

    @Autowired
    loginService l;
    @RequestMapping(value ="/login",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult helloHtml(@RequestBody User user) {
        String account=user.getName();
        String password=user.getPassword();
        UsernamePasswordToken token = new UsernamePasswordToken(account,password,false);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(token);
            AjaxResult result=new AjaxResult();
            result.put("msg","登录成功");
            result.put("code",200);
            result.put("token",currentUser.getSession().getId());
            result.put("role",l.selectUserByUserName(account).getRoleList());
            return result;
            //此步将 调用realm的认证方法
        } catch(IncorrectCredentialsException e){
            //这最好把 所有的 异常类型都背会
            return AjaxResult.error(500,"账号密码错误");
        } catch (AuthenticationException e) {

            return AjaxResult.error(500,"账号密码错误");
        }

    }

    /**
     * 未登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
     * @return
     */
    @RequestMapping(value = "/unauth")
    @ResponseBody
    public AjaxResult unauth() {
        AjaxResult result = new AjaxResult();
        result.put("code",100000);
        result.put("msy","未登录");
        return result;
    }



    @GetMapping("/testPermission")
    public String textPermission(){
        System.out.println("目前的账号是"+ ShiroUtils.getSubject().getPrincipal());
        System.out.println("目前的id是"+ ShiroUtils.getSubject().getSession().getId());
        return "index";

    }

}
